﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AccessToDataLibrary;
using Common;

namespace Library
{
    public partial class Client : Form
    {
        AccessToDataLibrary.AccessToDataLibrary accessToDataLibrary;
        NewArticle newArticle;

        public Client()
        {
            InitializeComponent();
            LogIn logIn = new LogIn();
            if (logIn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                accessToDataLibrary = new AccessToDataLibrary.
                    AccessToDataLibrary(logIn.DBtype, logIn.connectionParamaters);
            }
        }

        private void addNewBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewBook newBook = new NewBook();
            if (newBook.ShowDialog() == DialogResult.OK &&  newBook.NewBook_.Count >0)
            {
                accessToDataLibrary.AddBook(newBook.NewBook_);
                RefreshBooks_btn_Click(null, null);
            }
            else
                MessageBox.Show("Нет новых книг для сохранения.");  
        }
        private void updateBookToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Book oldBook = new Book();
            oldBook.ID = new Guid(Books_dgv.CurrentRow.Cells["ID"].Value.ToString());
            oldBook.ISBN = Books_dgv.CurrentRow.Cells["ISBN"].Value.ToString();
            oldBook.Name = Books_dgv.CurrentRow.Cells["Name"].Value.ToString();
            oldBook.Publisher = Books_dgv.CurrentRow.Cells["Publisher"].Value.ToString();
            oldBook.PublishedDate = DateTime.Parse(Books_dgv.CurrentRow.Cells["PublishedDate"].Value.ToString());
            oldBook.AuthorName = Books_dgv.CurrentRow.Cells["AuthorName"].Value.ToString();

            UpdateBook updateBook = new UpdateBook(oldBook);
            if (updateBook.ShowDialog() == DialogResult.OK)
            {
                List<Book> updatableBooks = new List<Book>();
                updatableBooks.Add(updateBook.NewBook);
                accessToDataLibrary.UpdateBooks(updatableBooks);
            }
            RefreshBooks_btn_Click(null, null);
        }
        private void RefreshBooks_btn_Click(object sender, EventArgs e)
        {
            if (accessToDataLibrary == null)
                return;

            List<Book> allBooks;
            if (
                (sender == null && e == null) ||
                (NameBook_txbx.Text.Trim() == string.Empty &&
                PublisherBook_txbx.Text.Trim() == string.Empty &&
                AuthorBook_txbx.Text.Trim() == string.Empty)
                )
            {
                allBooks = accessToDataLibrary.GetAllBooks();
                Books_dgv.DataSource = allBooks;
            }

            else
            {
                Book searchedBook = new Book(NameBook_txbx.Text.Trim(), PublisherBook_txbx.Text,
                    (PublishedDateBook_txbx.Text== "  .  ." ? DateTime.MinValue : DateTime.Parse(PublishedDateBook_txbx.Text)),
                    null, AuthorBook_txbx.Text.Trim());

                allBooks = accessToDataLibrary.GetSearchedBooks(searchedBook);
            }
            if (allBooks != null && allBooks.Count != 0)
            {
                Books_dgv.DataSource = allBooks;
            }

            if (Books_dgv.Columns != null && Books_dgv.Columns.Count != 0)
            {
                Books_dgv.Columns["ItemFields"].Visible = false;
                Books_dgv.Columns["AuthorFields"].Visible = false;
                Books_dgv.Columns["BookFields"].Visible = false;
                Books_dgv.Columns["ID"].Visible = false;
            }
        }
        private void RefreshMag_btn_Click(object sender, EventArgs e)
        {
            if (accessToDataLibrary == null)
                return;

            List<Magazine> allMagazines;

            if ((sender == null && e == null) ||
                (NameMag_txbx.Text.Trim() == string.Empty &&
                 PublisherMag_txbx.Text.Trim() == string.Empty &&
                 PublishedDateMag_txbx.Text.Trim() == string.Empty &&
                 IssueNumberMag_txbx.Text.Trim() == string.Empty))
            {
                allMagazines = accessToDataLibrary.GetAllMagazines();
            }
            else
            {
                Magazine searchedMagazine = new Magazine(NameMag_txbx.Text.Trim(), PublisherMag_txbx.Text.Trim(),
                    DateTime.Parse(PublishedDateMag_txbx.Text.Trim()), IssueNumberMag_txbx.Text.Trim());

                allMagazines = accessToDataLibrary.GetSearchedMagazines(searchedMagazine);
            }

            if (allMagazines != null)
            {
                Magazines_dgv.DataSource = allMagazines;
            }
            if (Magazines_dgv.Columns != null)
            {
                Magazines_dgv.Columns["ItemFields"].Visible =false;
                Magazines_dgv.Columns["MagazineFields"].Visible =false;
            }

        }
        private void RefreshArt_btn_Click(object sender, EventArgs e)
        {
            if (accessToDataLibrary == null)
                return;
            List<Article> allArticles = new List<Article>();

            if ((sender == null && e == null) ||
                NameArt_txbx.Text.Trim() == string.Empty &&
                PublisherArt_txbx.Text.Trim() == string.Empty &&
                PublishedDateArt_txbx.Text.Trim() == string.Empty &&
                AuthorArt_txbx.Text.Trim() == string.Empty)
            {
                allArticles = accessToDataLibrary.GetAllArticles();
            }
            else
            {
                Article searchedArticle = new Article(NameArt_txbx.Text.Trim(), PublisherArt_txbx.Text.Trim(),
                    DateTime.Parse(PublishedDateArt_txbx.Text.Trim()), null, null, AuthorArt_txbx.Text.Trim(), null);

                allArticles = accessToDataLibrary.GetSearchedArticles(searchedArticle);
            }

            if (allArticles != null)
            { 
                Articles_dgv.DataSource = allArticles;
            }
            if (Articles_dgv.Columns != null && Articles_dgv.Columns.Count > 0)
            {
                Articles_dgv.Columns["ItemFields"].Visible = false;
                Articles_dgv.Columns["MagazineFields"].Visible = false;
                Articles_dgv.Columns["AuthorFields"].Visible = false;
                Articles_dgv.Columns["ArticleFields"].Visible = false; 
                Articles_dgv.Columns["ID"].Visible = false;

            }
        }

        private void addNewMagazineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewMagazine newMagazine = new NewMagazine();

            if (newMagazine.ShowDialog() == System.Windows.Forms.DialogResult.OK && newMagazine.NewMag.Count > 0)
            {
                List<Magazine> notAddedMag = accessToDataLibrary.AddMagazine(newMagazine.NewMag);
                RefreshMag_btn_Click(null, null);
                if (notAddedMag.Count != 0)
                {
                    MessageBox.Show("Некоторые журналы не были сохранены в БД.");
                    NoAddedItems noAdIt = new NoAddedItems(notAddedMag);
                    noAdIt.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show("Нет новых журналов для сохранения.");
            }
        }

        private void addNewArticleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newArticle = new NewArticle(accessToDataLibrary.GetAllMagazinesNames());

            newArticle.SelectMagName += new SelectItem(newArticle_SelectMagName);
            if (newArticle.ShowDialog() == DialogResult.OK && newArticle.newArticles.Count > 0)
            {
                accessToDataLibrary.AddArticle(newArticle.newArticles);
            }
            else
            {
                MessageBox.Show("Нет статей для сохранения.");
            }
            RefreshArt_btn_Click(null, null);
            newArticle.SelectMagName -= new SelectItem(newArticle_SelectMagName);
        }

        void newArticle_SelectMagName(object sender, EventArgs e)
        {
            newArticle.IssueNum_ltbx.DataSource = accessToDataLibrary.GetCurrentMagazineAllIssueNumber(
                ((ListBox)sender).SelectedValue.ToString());
        }

        private void показатьВсеКопииToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string bookName;
            List<Copie> bookCopies = accessToDataLibrary.GetBookCopies(new Guid(Books_dgv["ID", rowIndex.Y].FormattedValue.ToString()),
                out bookName);
            List<User> users = accessToDataLibrary.GetAllUsers();
            CopiesBook copBook = new CopiesBook(bookCopies,bookName,users);
            copBook.BorrowingCopie += new BorCopie(copBook_BorrowingCopie);
            copBook.ShowDialog();
            copBook.BorrowingCopie += new BorCopie(copBook_BorrowingCopie);
        }

        void copBook_BorrowingCopie(List<BorrowedCopie> BorCops)
        {
            accessToDataLibrary.BorrowingBook(BorCops);
        }


        Point rowIndex = new Point();
        private void Books_dgv_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            rowIndex.X = e.ColumnIndex;
            rowIndex.Y = e.RowIndex;
        }
        UsersBorrowed borCop;
        private void showUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            borCop = new UsersBorrowed(accessToDataLibrary.GetAllUsers());
            borCop.SelectUserName += new SelectItem(borCop_SelectUserName);
            if (borCop.ShowDialog() == DialogResult.OK)
            {
                accessToDataLibrary.ReturnBooks(borCop.returnedItem);
            }
            borCop.SelectUserName -= new SelectItem(borCop_SelectUserName);
        }

        void borCop_SelectUserName(object sender, EventArgs e)
        {
            borCop.AllBorrowedCopieByUser_dgv.DataSource =
                accessToDataLibrary.GetAllBorrowedCopiesByUser(new Guid(((ListBox)sender).SelectedValue.ToString()));
        }

        private void addNewUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewUser newUser = new NewUser();
            if (newUser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (accessToDataLibrary.AddUser(newUser.NewUser_))
                    MessageBox.Show("Новый пользователь создан.");
                else
                    MessageBox.Show("Новый пользователь не создан.");
            }

        }

        private void Client_Load(object sender, EventArgs e)
        {
            Authorization authorization = new Authorization(accessToDataLibrary);
            if (authorization.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                RefreshBooks_btn_Click(null, null);
                RefreshMag_btn_Click(null, null);
                RefreshArt_btn_Click(null, null);
                if (!authorization.user.IsAdmin)
                {
                    for (int i = 1; i < menuStrip1.Items.Count; i++)
                    {
                        menuStrip1.Items[i].Enabled = false;
                    }
                }
                else
                {
                    Books_dgv.ContextMenuStrip = Book_cntMstr;
                }
            }
            else
            {
                this.Close();
            }
        }
    }
}

